import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class QoSTalker(Node):
    def __init__(self):
        super().__init__('qos_talker')
        self.publisher = self.create_publisher(String, 'qos_chatter', self.get_qos_profile())
        timer_period = 1  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)

    def get_qos_profile(self):
        # 设置QoS配置：这里设置为Best Effort，不保证消息的可靠性
        qos_profile = rclpy.qos.QoSProfile(depth=10)
        qos_profile.reliability = rclpy.qos.ReliabilityPolicy.BEST_EFFORT
        qos_profile.history = rclpy.qos.HistoryPolicy.KEEP_LAST
        return qos_profile

    def timer_callback(self):
        msg = String()
        msg.data = 'Hello, ROS 2 Humble with QoS!'
        self.publisher.publish(msg)
        self.get_logger().info('Publishing: "%s"' % msg.data)

def main(args=None):
    rclpy.init(args=args)
    qos_talker = QoSTalker()

    rclpy.spin(qos_talker)
    qos_talker.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()